<?php
namespace Common\Logic;

/**
 * 影院放映厅模型 
 */
class CinemaLogic{
    
    //获取影院用户列表
    public function getCinemaList($params){
        $result = array();
        $current_time = time();
        $model = M();
        //查询语句
        $select_sql = "";
        $order_sql = "";
        //组织查询条件sql
        if(array_key_exists('keywords', $params) && $params['keywords'])
        {
            $select_sql .= " AND (a.host_name LIKE '%%".$params['keywords']."%%' OR a.cinema_name LIKE '%%".$params['keywords']."%%')";
        }
		if($params['keywords'] == '0'){
			 $select_sql .= " AND (a.host_name LIKE '%%".$params['keywords']."%%' OR a.cinema_name LIKE '%%".$params['keywords']."%%')";
		}
        if(array_key_exists('status', $params))
        {
            $select_sql .= " AND (a.status = '".$params['status']."')";
        }
        if(array_key_exists('hoststatus', $params) && $params['hoststatus'] == 1)
        {
			$check_time = $current_time - 1800;
            $select_sql .= " AND (a.refresh_time >= ".$check_time.")";
        }
		elseif((array_key_exists('hoststatus', $params) && $params['hoststatus'] == 2))
		{
			$check_time = $current_time - 1800;
			$select_sql .= " AND (a.refresh_time < ".$check_time.")";
		}		
        if(array_key_exists('recharge_type', $params))
        {
            $select_sql .= " AND (a.recharge_type = '".$params['recharge_type']."')";
        }
        if(isset($params['create_time_start']) && !empty($params['create_time_start']))
        {
            $select_sql .= " AND (a.join_time >= ".strtotime($params['create_time_start']).")";
        }
        if(isset($params['create_time_end']) && !empty($params['create_time_end']))
        {
            $create_time_end = strtotime($params['create_time_end']);
            $create_time_end += 86400;
            $select_sql .= " AND (a.join_time <= ".$create_time_end.")";
        }
        if(array_key_exists('type', $params))
        {
            $select_sql .= " AND (a.type = '".$params['type']."')";
        }
		if(array_key_exists('not_types', $params))
        {
            $select_sql .= " AND (a.type NOT IN (".$params['not_types']."))";
        }
        if($params['CopyrightIndustryOptions']>0){
            $select_sql .= " AND (a.video_copyright_industry =(".$params['CopyrightIndustryOptions']."))";
        }
        
        //查询语句
        $sql = "SELECT %s
                FROM mt_cinema_host AS a 
                WHERE 1".$select_sql." ORDER BY a.id DESC";
        //统计个数，准备分页
        $field_aql = "COUNT(*) AS count";
        $current_sql = sprintf($sql,$field_aql);
        $rs_count = $model->query($current_sql);
        $count = $rs_count[0]['count'];
		
		//统计平台影院数量
		$map = $select_sql ;
		$map.= " AND (a.agent_id = 0)";
        $sql_one = "SELECT %s
                FROM mt_cinema_host AS a 
                WHERE 1".$map." ORDER BY a.id DESC";
        $field_aql_one = "COUNT(*) AS count";
        $current_sql_one = sprintf($sql_one,$field_aql_one);
        $rs_count_one = $model->query($current_sql_one);
        $pingcount = $rs_count_one[0]['count'];		
		//统计代理商影院数量
		$temp = $select_sql ;
		$temp.= " AND (a.agent_id <> 0)";
        $sql_two = "SELECT %s
                FROM mt_cinema_host AS a 
                WHERE 1".$temp." ORDER BY a.id DESC";
        $field_aql_two = "COUNT(*) AS count";
        $current_sql_two = sprintf($sql_two,$field_aql_two);
        $rs_count_two = $model->query($current_sql_two);
        $agentcount = $rs_count_two[0]['count'];
		
        if(isset($params['page']))
        {
            $_GET['p'] = $params['page'];
        }
        !$params['page_size'] && $params['page_size'] = 15;
        $pager = new \Think\Page2($count, $params['page_size']);
        //查询数据
        $field_aql = "a.*";
        $current_sql = sprintf($sql,$field_aql);
        $current_sql .= " LIMIT ".$pager->firstRow.",".$pager->listRows;
        $data_list = array();
        $data_list = $model->query($current_sql);
        //echo $model->getLastSql();
        if(!empty($data_list))
        {
			$current_time = time();
            foreach($data_list as $key => $value)
            {
                $temp = $value;
				
				
				$temp['current_cost_money'] = '--';
				$temp['current_end_day'] = '--';
				//新模式
				if(0 < $temp['last_cost_time']
				   && 0 < $temp['buy_hall_count']
				   && 0 == $temp['recharge_method_id']) {
					//本期扣费金额
					$temp['current_cost_money'] = $temp['hall_price']*$temp['buy_hall_count']*$temp['deduct_period'];
					//本期截止日期
					$temp['current_end_day'] = date('Y-m-d', $temp['last_cost_time']+86400*$temp['deduct_period_day']);
				}
				
                $data_list[$key] = $temp;
            }
        }
        $result['count'] = $count;
		$result['pingcount'] = $pingcount;
		$result['agentcount'] = $agentcount;
        $result['data_list'] = $data_list;
        $result['pager'] = $pager->show();
        
        return $result;
    }
    
    /**
     * 添加影院用户
     * @param  array
     * @return array
     * @author ming.nie
     */
    public function add($params){
        $result = array();
        $result_manager = array(
            0 => array('status_code'=>0,'status_message'=>'添加失败'),
            1 => array('status_code'=>1,'status_message'=>'添加成功'),
            3 => array('status_code'=>3,'status_message'=>'参数错误'),
            4 => array('status_code'=>4,'status_message'=>'主机名重复'),
        );
        $status_code = 0;
        if(isset($params['host_name']) && !empty($params['host_name'])
           && isset($params['user_id']) && !empty($params['user_id'])) {
            $model = M('CinemaHost');
            
            //验证是否存在重复主机名
			$condition = array();
			$condition['host_name'] = $params['host_name'];
			$check_host_name = $model->where($condition)->find();
            
            if(!$check_host_name) {
                $current_time = time();
				
				//计算计费周期天数_下次
				$params['deduct_period_day'] = $params['deduct_period']*31;
				
				//新加用户状态为已停用
				$params['status'] = 2;
				
                //初始化数据
                $params['join_time'] = $current_time;
                $params['next_recharge_method_id'] = 0;
                $params['create_user_id'] = $params['user_id'];
                $params['create_time'] = $current_time;
                $params['update_user_id'] = $params['user_id'];
                $params['update_time'] = $current_time;
                unset($params['user_id']);

                $model->data($params);
                $db_result = $model->add();
                if($db_result) {
                    $status_code = 1;
                    $result_manager[1]['id'] = $db_result;
					//记录用户日志
					addUserLog();
                }
            } else {
                $status_code = 4;
            }
            
        } else {
            $status_code = 3;
        }
        $result = array_merge($result,$result_manager[$status_code]);
        return $result;
    }
    
    /**
     * 编辑影院用户
     * @param  array
     * @return array
     * @author ming.nie
     */
    public function edit($params){
        $result = array();
        $result_manager = array(
            0 => array('status_code'=>0,'status_message'=>'编辑失败'),
            1 => array('status_code'=>1,'status_message'=>'编辑成功'),
            3 => array('status_code'=>3,'status_message'=>'参数错误'),
        );
        $status_code = 0;
        if(isset($params['id']) && !empty($params['id'])
           && isset($params['user_id']) && !empty($params['user_id'])) {
            $model = M('CinemaHost');
			$agentUserModel = M('AgentUser');
			$current_time = time();
            
            //查询当前影院信息
            $cinema = $this->find($params['id']);
            
            //重置下次计费方式，后面业务逻辑，会基于当前计费方式与历史计费方式进行更新。
            $params['next_recharge_method_id'] = 0;
            $params['update_user_id'] = $params['user_id'];
            $params['update_time'] = $current_time;
            unset($params['user_id']);
            $model->data($params);
            $db_result = $model->where('id = "'.$params['id'].'"')->save();
            if($db_result) {
                $status_code = 1;
				
				//查询影院相关代理商用户
				$agent_cinema_user_ids = array();
				$agent_cinema_user_sql = 'SELECT user_id FROM mt_agent_user WHERE platform=5 AND cinema_id = "'.$params['id'].'"';
				$agent_cinema_user_rs = $agentUserModel->query($agent_cinema_user_sql);
				if($agent_cinema_user_rs) {
					foreach($agent_cinema_user_rs as $key => $value) {
						$agent_cinema_user_ids[] = $value['user_id'];
					}
					$agent_cinema_user_ids = implode(',', $agent_cinema_user_ids);
					$is_change_agent = 0;
					
					//echo $cinema['agent_id']." -> ".$params['agent_id']."\r\n";
					//echo $cinema['agent_level_1']." -> ".$params['agent_level_1']."\r\n";
					//echo $cinema['agent_level_2']." -> ".$params['agent_level_2']."\r\n";
					
					//基于影院代理商信息编辑，进行代理商用户系统用户代理信息更新
					//case 1
					if($cinema['agent_id'] == $params['agent_id']
					   && $cinema['agent_level_1'] == $params['agent_level_1']
					   && $cinema['agent_level_2'] != $params['agent_level_2']) {
						$condition = array();
						$condition['user_id'] = array('in', $agent_cinema_user_ids);
						$update_data = array();
						$update_data['agent_level_2'] = $params['agent_level_2'];
						$agentUserModel->data($update_data)->where($condition)->save();
						$is_change_agent = 1;
					}
					//case 2
					if($cinema['agent_id'] == $params['agent_id']
					   && $cinema['agent_level_1'] != $params['agent_level_1']
					   && $cinema['agent_level_2'] != $params['agent_level_2']) {
						$condition = array();
						$condition['user_id'] = array('in', $agent_cinema_user_ids);
						$update_data = array();
						$update_data['agent_level_1'] = $params['agent_level_1'];
						$update_data['agent_level_2'] = $params['agent_level_2'];
						$agentUserModel->data($update_data)->where($condition)->save();
						$is_change_agent = 1;
					}
					//case 3
					if($cinema['agent_id'] == $params['agent_id']
					   && $cinema['agent_level_1'] == $params['agent_level_1']
					   && 0 == $params['agent_level_2']) {
						$condition = array();
						$condition['user_id'] = array('in', $agent_cinema_user_ids);
						$update_data = array();
						$update_data['agent_level_1'] = $params['agent_level_1'];
						$update_data['agent_level_2'] = 0;
						$agentUserModel->data($update_data)->where($condition)->save();
						$is_change_agent = 1;
					}
					//case 4
					if($cinema['agent_id'] == $params['agent_id']
					   && $cinema['agent_level_1'] != $params['agent_level_1']
					   && 0 == $params['agent_level_2']) {
						$condition = array();
						$condition['user_id'] = array('in', $agent_cinema_user_ids);
						$update_data = array();
						$update_data['agent_level_1'] = $params['agent_level_1'];
						$update_data['agent_level_2'] = 0;
						$agentUserModel->data($update_data)->where($condition)->save();
						$is_change_agent = 1;
					}
					//case 5
					if($cinema['agent_id'] == $params['agent_id']
					   && 0 == $params['agent_level_1']
					   && 0 == $params['agent_level_2']) {
						$condition = array();
						$condition['user_id'] = array('in', $agent_cinema_user_ids);
						$update_data = array();
						$update_data['agent_level_1'] = 0;
						$update_data['agent_level_2'] = 0;
						$agentUserModel->data($update_data)->where($condition)->save();
						$is_change_agent = 1;
					}
					//case 6
					if($cinema['agent_id'] != $params['agent_id']) {
						$condition = array();
						$condition['user_id'] = array('in', $agent_cinema_user_ids);
						$update_data = array();
						$update_data['agent_id'] = $params['agent_id'];
						$update_data['agent_level_1'] = $params['agent_level_1'];
						$update_data['agent_level_2'] = $params['agent_level_2'];
						$agentUserModel->data($update_data)->where($condition)->save();
						$is_change_agent = 1;
					}
					//case 7 -> 1
					
					//case 8 -> 2
					
					//case 9 -> 6
					
					//case 10 -> 4
					
					//case 11 -> 6
					
					//case12 -> 5
					
					//case13 -> 6
					
					//case14 -> 6
					
					//case15 -> 4
					
					//case16 -> 11
					
					//case17 -> 2
					
					//case18 -> 9
					
					//如果更新了代理商信息，更新影院相关代理商业务信息
					if(1 == $is_change_agent) {
						D('Common/AgentRebate', 'Logic')->setAgentCinemaMoney($params['id']);
					}
				}
				
				//记录用户日志
				addUserLog();
            }
        } else {
            $status_code = 3;
        }
        $result = array_merge($result,$result_manager[$status_code]);
        return $result;
    }
    
    /**
     * 更新影院用户
     * @param  array
     * @return array
     * @author ming.nie
     */
    public function update($params){
        $result = array();
        $result_manager = array(
            0 => array('status_code'=>0,'status_message'=>'操作失败'),
            1 => array('status_code'=>1,'status_message'=>'操作成功'),
            3 => array('status_code'=>3,'status_message'=>'参数错误'),
        );
        $status_code = 0;
        if(isset($params['id']) && !empty($params['id'])
           && isset($params['user_id']) && !empty($params['user_id'])) {
            $model = M('CinemaHost');
            
            $current_time = time();
            $params['update_user_id'] = $params['user_id'];
            $params['update_time'] = $current_time;
            unset($params['user_id']);
            $model->data($params);
            $db_result = $model->where('id = "'.$params['id'].'"')->save();
            if($db_result) {
                $status_code = 1;
				//记录用户日志
				addUserLog();
            }
            
        } else {
            $status_code = 3;
        }
        $result = array_merge($result,$result_manager[$status_code]);
        return $result;
    }
    
    /**
     * 查找影院用户基于ID
     * @param  array
     * @return array
     * @author ming.nie
     */
    public function find($id){
        $model = M('CinemaHost');
        $result = $model->find($id);
		if($result) {
			//影院影片版权区域选项
			if($result['video_copyright_area']) {
				$result['video_copyright_area_arr'] = explode(',', $result['video_copyright_area']);
			} else {
				$result['video_copyright_area_arr'] = array();
			}
			
			//影院影片版权行业选项
			if($result['video_copyright_industry']) {
				$result['video_copyright_industry_arr'] = explode(',', $result['video_copyright_industry']);
			} else {
				$result['video_copyright_industry_arr'] = array();
			}
			
			//影院签署版权商
			if($result['copyright_user_ids']) {
				$result['copyright_user_ids_arr'] = explode(',', $result['copyright_user_ids']);
			} else {
				$result['copyright_user_ids_arr'] = array();
			}
		}
        return $result;
    }
    
    /**
     * 查找影院用户基于参数
     * @param  array
     * @return array
     * @author ming.nie
     */
    public function findByAttr($params){
        $model = M('CinemaHost');
        $result = array();
        $condition = array();
        if(array_key_exists('host_name', $params)) {
            $condition['host_name'] = $params['host_name'];
        }
        if(!empty($condition)) {
            $result = $model->where($condition)->find();
        }
        return $result;
    }
    
	/**
     * 计费变更
     * @param  array
     * @return array
     * @author ming.nie
     */
    public function changeRecharge($params){
        $result = array();
        $result_manager = array(
            0 => array('status_code'=>0,'status_message'=>'编辑失败'),
            1 => array('status_code'=>1,'status_message'=>'编辑成功'),
            3 => array('status_code'=>3,'status_message'=>'参数错误'),
        );
        $status_code = 0;
        if(isset($params['id']) && !empty($params['id'])) {
            $model = M('CinemaHost');
            
            //查询当前影院信息
            $cinema = $this->find($params['id']);
            
            $current_time = time();
			
			//计算计费周期天数_下次
			$params['deduct_period_day_next'] = $params['deduct_period_next']*31;
			
            $params['update_user_id'] = $params['user_id'];
            $params['update_time'] = $current_time;
            unset($params['user_id']);
			
            $model->data($params);
            $db_result = $model->where('id = "'.$params['id'].'"')->save();
            if($db_result) {
                $status_code = 1;
            }
        } else {
            $status_code = 3;
        }
        $result = array_merge($result,$result_manager[$status_code]);
        return $result;
    }
	
    /**
     * 获取计费方式列表
     * @param  array
     * @return array
     * @author ming.nie
     */
    public function getRechargeMethodList($params){
        $result = array();
        
        $model = M();
        //查询语句
        $select_sql = "";
        $order_sql = "";
        //组织查询条件sql
        if(array_key_exists('keywords', $params) && !$params['keywords']) {
            $select_sql .= " AND (a.recharge_method_name LIKE '%%".$params['v']."%%')";
        }
		if(array_key_exists('recharge_method_id', $params)) {
			$select_sql .= " AND (a.recharge_method_id = '".$params['recharge_method_id']."')";
		}
		if(array_key_exists('recharge_method_ids', $params)) {
			$select_sql .= " AND (a.recharge_method_id IN (".$params['recharge_method_ids']."))";
		}
        if(array_key_exists('status', $params)) {
            $select_sql .= " AND (a.status = '".$params['status']."')";
        }
        
        //查询语句
        $sql = "SELECT %s
                FROM mt_recharge_method AS a 
                WHERE 1".$select_sql." ORDER BY a.recharge_method_id ASC";
        //统计个数，准备分页
        $field_aql = "COUNT(*) AS count";
        $current_sql = sprintf($sql,$field_aql);
        $rs_count = $model->query($current_sql);
        $count = $rs_count[0]['count'];
        if(isset($params['page']))
        {
            $_GET['p'] = $params['page'];
        }
        !$params['page_size'] && $params['page_size'] = 15;
        $pager = new \Think\Page($count, $params['page_size']);
        //查询数据
        $field_aql = "a.*";
        $current_sql = sprintf($sql,$field_aql);
        $current_sql .= " LIMIT ".$pager->firstRow.",".$pager->listRows;
        $data_list = array();
        $data_list = $model->query($current_sql);
        //echo $model->getLastSql();
        if(!empty($data_list))
        {
            foreach($data_list as $key => $value)
            {
                $temp = $value;
                $data_list[$key] = $temp;
            }
        }
        
        $result['count'] = $count;
        $result['data_list'] = $data_list;
        $result['pager'] = $pager->show();
        
        return $result;
    }
    
    /**
     * 添加计费方式
     * @param  array
     * @return array
     * @author ming.nie
     */
    public function addRechargeMethod($params){
        $result = array();
        $result_manager = array(
            0 => array('status_code'=>0,'status_message'=>'添加失败'),
            1 => array('status_code'=>1,'status_message'=>'添加成功'),
            3 => array('status_code'=>3,'status_message'=>'参数错误'),
            4 => array('status_code'=>4,'status_message'=>'收费方式重复'),
        );
        $status_code = 0;
        if(isset($params['recharge_method_name']) && !empty($params['recharge_method_name'])
           && isset($params['cost_type']) && !empty($params['cost_type'])
           && isset($params['user_id']) && !empty($params['user_id'])) {
            $model = M('RechargeMethod');
            //验证是否存在重复收费方式
            $condition = array();
            $condition['recharge_method_name'] = $params['recharge_method_name'];
            $check_recharge_method_name = $model->where($condition)->find();
            if($check_recharge_method_name) {
                $status_code = 4;
            } else {
                $current_time = time();
                //如果是按时间段计费，计算具体时间段
                if(2 == $params['cost_type']) {
                    if(2 == $params['time_type']) {
                        $params['day_count'] = 31 * $params['time_count'];
                    } else {
                        $params['day_count'] = $params['time_count'];
                    }
                }
                $params['create_user_id'] = $params['user_id'];
                $params['update_user_id'] = $params['user_id'];
                $params['create_time'] = $current_time;
                $params['update_time'] = $current_time;
                unset($params['user_id']);
                $model->data($params);
                $db_result = $model->add();
                if($db_result) {
                    $status_code = 1;
                }
            }
        } else {
            $status_code = 3;
        }
        $result = array_merge($result,$result_manager[$status_code]);
        return $result;
    }
    
    /**
     * 更新计费方式
     * @param  array
     * @return array
     * @author ming.nie
     */
    public function updateRechargeMethod($params){
        $result = array();
        $result_manager = array(
            0 => array('status_code'=>0,'status_message'=>'操作失败'),
            1 => array('status_code'=>1,'status_message'=>'操作成功'),
            3 => array('status_code'=>3,'status_message'=>'参数错误'),
        );
        $status_code = 0;
        if(isset($params['recharge_method_id']) && !empty($params['recharge_method_id'])
           && isset($params['user_id']) && !empty($params['user_id'])) {
            $model = M('RechargeMethod');
            $current_time = time();
            $params['update_user_id'] = $params['admin_user_id'];
            $params['update_time'] = $current_time;
            unset($params['user_id']);
            $model->data($params);
            $db_result = $model->where('recharge_method_id = "'.$params['recharge_method_id'].'"')->save();
            if($db_result) {
                $status_code = 1;
            }
        } else {
            $status_code = 3;
        }
        $result = array_merge($result,$result_manager[$status_code]);
        return $result;
    }
    
    /**
     * 查询计费方式
     * @param  int
     * @return array
     * @author ming.nie
     */
    public function findRechargeMethod($id){
        $model = M('RechargeMethod');
        $result = $model->find($id);
        return $result;
    }
    
    /**
     * 获取计费方式选项
     * @param  array
     * @return array
     * @author ming.nie
     */
    public function getRechargeMethodOptions($params){
        $rseult = array();
		if(array_key_exists('empty', $params)) {
			$rseult[0] = '包段付费模式';
		}
        $params['page'] = 1;
        $params['page_size'] = 1000;
        $data_list_data = $this->getRechargeMethodList($params);
        foreach($data_list_data['data_list'] as $key => $value){
            if(2 == $value['status']) {
                $value['recharge_method_name'] .= '(已停用)';
            }
            $rseult[$value['recharge_method_id']] = $value['recharge_method_name'];
        }
        return $rseult;
    }
    
    /**
     * 充值，消费
     * @param  array
     * @return array
     * @author ming.nie
     */
    public function recharge($params){
        $result = array();
        $result_manager = array(
            0 => array('status_code'=>0,'status_message'=>'充值失败'),
            1 => array('status_code'=>1,'status_message'=>'充值成功'),
            3 => array('status_code'=>3,'status_message'=>'充值参数错误'),
            4 => array('status_code'=>4,'status_message'=>'消费参数错误'),
        );
        $status_code = 0;
        if(isset($params['money']) && is_numeric($params['money'])
           && isset($params['recharge_type']) && !empty($params['recharge_type'])) {
            $model = M('RechargeLog');
			$current_time = time();
            
            //充值
            if(1 == $params['recharge_type']) {
                if(isset($params['img_url']) && !empty($params['img_url'])
                && isset($params['account_name']) && !empty($params['account_name'])
                && isset($params['account_number']) && !empty($params['account_number'])
                && isset($params['cinema_host_id']) && !empty($params['cinema_host_id'])
                && isset($params['user_id']) && !empty($params['user_id'])) {
                    $status_code = 0;
                } else {
                    $status_code = 4;
                }
            }
            
            //消费
            if(2 == $params['recharge_type']) {
                if(isset($params['user_id']) && !empty($params['user_id'])) {
                    $status_code = 0;
                } else {
                    $status_code = 4;
                }
            }
            
            //参数正确，进入下一步
            if(0 == $status_code)
            {
                //查询当前影院信息
                $cinemaHostModel = M('CinemaHost');
                $cinema = $this->find($params['cinema_host_id']);
                
				//按照规则，生成流水号
				$sn_count = 1;
				$sn_day = date('Ymd');
				$sn_count = substr($current_time, 4,10);
				$params['sn'] = $sn_day.'0'.$params['recharge_type'].$sn_count;
				
                //计算影厅当前余额
                $balance = $cinema['money'] + $params['money'];
                
                $params['balance'] = $balance;
                //$params['recharge_method_id'] = $cinema['recharge_method_id'];
                $params['create_user_id'] = $params['user_id'];
                $params['update_user_id'] = $params['user_id'];
                $params['create_time'] = $current_time;
                $params['update_time'] = $current_time;
                unset($params['user_id']);
                $model->data($params);
                $db_result = $model->add();
                if($db_result) {
                    $status_code = 1;
					
					//判断是否完成交易完成，如果没有，就是预更新金额，不进行正常的业务逻辑
					$is_complete = 1;
					if(array_key_exists('is_complete', $params)
					   && 0 == $params['is_complete']) {
						$is_complete = 0;
					}
					
					//交易完成
					if(1 == $is_complete) {
						//更新影院用户金额
						$update_data = array();
						$update_data['money'] = $balance;
						$condition = array();
						$condition['id'] = $params['cinema_host_id'];
						$cinemaHostModel->data($update_data)->where($condition)->save();
						
						//充值的时候，检测当前影院计费方式，与账户余额判断是否需要自动扣费
						$recharge_method = $this->findRechargeMethod($cinema['recharge_method_id']);
						if(1 == $params['recharge_type']
						   && 0 < $cinema['hall_price']) {
							$need_cost = 0;
							//基于最后扣费时间，判断是否需要自动扣费
							if(0 == $cinema['last_cost_time']) {
								$need_cost = 1;
							}
							
							//老模式：期限类，已扣款，判断是否超过期限。超期，就用新的计费方式扣费，并且取消老的选项计费方式
							if(!$need_cost
								&& $recharge_method) {
								$use_time = $current_time-$cinema['last_cost_time'];
								$use_date = ceil($use_time/86400);
								if($use_date > $recharge_method['day_count']) {
									$need_cost = 1;
									$update_data = array();
									$update_data['last_cost_time'] = 0;
									$update_data['recharge_method_id'] = 0;
									$update_data['next_recharge_method_id'] = 0;
									$condition = array();
									$condition['id'] = $params['cinema_host_id'];
									$cinemaHostModel->data($update_data)->where($condition)->save();
								}
							}
							
							//新模式：期限类，已扣款，判断是否超过期限。超期，用新的计费方式扣费
							if(!$need_cost
								&& !$recharge_method
								&& $cinema['hall_price']) {
								$use_time = $current_time-$cinema['last_cost_time'];
								$use_date = ceil($use_time/86400);
								if($use_date > $cinema['deduct_period_day']) {
									$need_cost = 1;
									$update_data = array();
									$update_data['last_cost_time'] = 0;
									$update_data['recharge_method_id'] = 0;
									$update_data['next_recharge_method_id'] = 0;
									$condition = array();
									$condition['id'] = $params['cinema_host_id'];
									$cinemaHostModel->data($update_data)->where($condition)->save();
								}
							}
							
							if(1 == $need_cost) {
								//查看是否有更新的计费方式，有的话，就用新的计费方式
								if(0 < $cinema['hall_price_next']) {
									$cinema['hall_price'] = $cinema['hall_price_next'];
									$cinema['buy_hall_count'] = $cinema['buy_hall_count_next'];
									$cinema['period_count'] = $cinema['period_count_next'];
									$cinema['deduct_period'] = $cinema['deduct_period_next'];
									$cinema['deduct_period_day'] = $cinema['deduct_period_day_next'];
								}
								
								//基于计费方式，计算每次扣款金额，金额够，扣款且更新状态为正常，否则更新状态为停用
								$deduct_money = $cinema['hall_price']*$cinema['buy_hall_count']*$cinema['deduct_period'];
								if($deduct_money) {
									if($balance >= $deduct_money) {
										$recharge_params = array();
										$recharge_params['money'] = -$deduct_money;
										$recharge_params['description'] = '影院：'.$cinema['host_name'].' ：按扣费周期扣款';
										$recharge_params['cinema_host_id'] = $params['cinema_host_id'];
										$recharge_params['recharge_type'] = 2;
										$recharge_params['recharge_method_id'] = 0;
										$recharge_params['user_id'] = 1;
										$sub_result = $this->recharge($recharge_params);
										if(1 == $sub_result['status_code']) {
											//更新影院最后扣费时间
											$update_data = array();
											$update_data['status'] = 1;
											$update_data['last_cost_time'] = $current_time;
											$update_data['deduct_period_day'] = $cinema['deduct_period']*31;
											
											//查看是否有更新的计费方式，有的话，就更新老的，清空旧的
											if(0 < $cinema['hall_price_next']) {
												$update_data['hall_price'] = $cinema['hall_price_next'];
												$update_data['buy_hall_count'] = $cinema['buy_hall_count_next'];
												$update_data['period_count'] = $cinema['period_count_next'];
												$update_data['deduct_period'] = $cinema['deduct_period_next'];
												
												$update_data['hall_price_next'] = 0;
												$update_data['buy_hall_count_next'] = 0;
												$update_data['period_count_next'] = 0;
												$update_data['deduct_period_next'] = 0;
												$update_data['deduct_period_day_next'] = 0;
											}
											
											
											$condition = array();
											$condition['id'] = $params['cinema_host_id'];
											$cinemaHostModel->data($update_data)->where($condition)->save();
										}
									} else {
										$update_data = array();
										$update_data['status'] = 2;
										$condition = array();
										$condition['id'] = $params['cinema_host_id'];
										$cinemaHostModel->data($update_data)->where($condition)->save();
									}
								}
							}
						}
					}
                }
            }
        } else {
            $status_code = 3;
        }
        $result = array_merge($result,$result_manager[$status_code]);
        return $result;
    }
    
    //获取影院用户充值列表
    public function getRechargeList($params){
        $result = array();
        
        $model = M();
        //查询语句
        $select_sql = "";
        $order_sql = "";
        //组织查询条件sql
        if(array_key_exists('keywords', $params) && $params['keywords'])
        {
             $select_sql .= " AND (c.host_name LIKE '%%".$params['keywords']."%%')";
        }
		if($params['keywords'] == '0'){
			$select_sql .= " AND (c.host_name LIKE '%%".$params['keywords']."%%')";
		}
        if(array_key_exists('cinema_host_id', $params))
        {
            $select_sql .= " AND (a.cinema_host_id = '".$params['cinema_host_id']."')";
        }
        if(array_key_exists('recharge_type', $params))
        {
            $select_sql .= " AND (a.recharge_type = '".$params['recharge_type']."')";
        }
        if(array_key_exists('recharge_from', $params)  &&  $params['recharge_from'] != 0)
        {
            $select_sql .= " AND (a.recharge_from = '".$params['recharge_from']."')";
        }
        if(array_key_exists('status', $params))
        {
			if($params['status'] == 1){
				 $select_sql .= " AND (a.status = 1)";
			}elseif($params['status'] == 2){
				$select_sql .= " AND (a.status = 0)";
			}
           
        }			
        if(isset($params['create_time_start']) && !empty($params['create_time_start']))
        {
            $select_sql .= " AND (a.create_time >= ".strtotime($params['create_time_start']).")";
        }
        if(isset($params['create_time_end']) && !empty($params['create_time_end']))
        {
            $create_time_end = strtotime($params['create_time_end']);
            $create_time_end += 86400;
            $select_sql .= " AND (a.create_time <= ".$create_time_end.")";
        }
        
        //查询语句
        $sql = "SELECT %s
                FROM mt_recharge_log AS a
                LEFT JOIN mt_user AS b ON a.create_user_id = b.user_id 
                LEFT JOIN mt_cinema_host AS c ON a.cinema_host_id = c.id
                LEFT JOIN mt_recharge_method AS d ON a.recharge_method_id = d.recharge_method_id 
                WHERE 1".$select_sql." ORDER BY a.recharge_log_id DESC";
        //统计个数，准备分页
        $field_aql = "COUNT(*) AS count";
        $current_sql = sprintf($sql,$field_aql);
        $rs_count = $model->query($current_sql);
        $count = $rs_count[0]['count'];
        if(isset($params['page']))
        {
            $_GET['p'] = $params['page'];
        }
        
        //统计金额
        $total_money_sql = "SELECT SUM(a.money) AS total_money 
                FROM mt_recharge_log AS a 
                LEFT JOIN mt_user AS b ON a.create_user_id = b.user_id 
                LEFT JOIN mt_cinema_host AS c ON a.cinema_host_id = c.id 
                LEFT JOIN mt_recharge_method AS d ON a.recharge_method_id = d.recharge_method_id 
                WHERE 1".$select_sql." ORDER BY a.recharge_log_id DESC";
        $rs = $model->query($total_money_sql);
        $result['total_money'] = number_format($rs[0]['total_money'], 0, '', '');
        
        !$params['page_size'] && $params['page_size'] = 15;
        $pager = new \Think\Page2($count, $params['page_size']);
        //查询数据
        $field_aql = "a.*,b.user_name AS executor,c.user_name AS cinema_user_name,d.recharge_method_name ";
        $current_sql = sprintf($sql,$field_aql);
        $current_sql .= " LIMIT ".$pager->firstRow.",".$pager->listRows;
        $data_list = array();
        $data_list = $model->query($current_sql);
        //echo $model->getLastSql();
        if(!empty($data_list))
        {
            foreach($data_list as $key => $value)
            {
                $temp = $value;
                $data_list[$key] = $temp;
            }
        }
        
        $result['count'] = $count;
        $result['data_list'] = $data_list;
        $result['pager'] = $pager->show();
        
        return $result;
    }
    
    /**
     * 查询充值详情
     * @param  array
     * @return array
     * @author ming.nie
     */
    public function findRechargeDetail($id){
        $model = M('RechargeLog');
        $result = $model->find($id);
        return $result;
    }
    
    /**
     * 接口：初始化放映厅(影院调用)
     * @param  array
     * @return array
     * @author ming.nie
     */
    public function initCinemaHost($params){
        $result = array();
        $result_manager = array(
            0 => array('status_code'=>0,'status_message'=>'初始化失败'),
            1 => array('status_code'=>1,'status_message'=>'初始化成功'),
            3 => array('status_code'=>3,'status_message'=>'参数错误'),
            4 => array('status_code'=>4,'status_message'=>'已初始化'),
        );
        $status_code = 0;
        if(isset($params['host_name']) && !empty($params['host_name'])) {
            //判断是否初始化
            $model = M('CinemaHost');
            $sql = 'SELECT * FROM mt_cinema_host WHERE host_name = "'.$params['host_name'].'"';
            $check_is_init = $model->query($sql);
            if($check_is_init) {
                $status_code = 4;
            } else {
                $data = array();
                $data['host_name'] = $params['host_name'];
				if(is_numeric(strpos($data['host_name'], 'xs-'))) {
					$data['type'] = 4;
				}
				if(is_numeric(strpos($data['host_name'], 'xl-'))) {
					$data['type'] = 8;
				}
                $data['money'] = 0;
                $data['status'] = 1;
				$data['create_time'] = time();
                $data['join_time'] = time();
                $db_result = $model->data($data)->add();
                if($db_result) {
                    $status_code = 1;
					if(is_numeric(strpos($data['host_name'], 'xs-'))) {
						$xs_hotel_params = array();
						$xs_hotel_params['host_name'] = $params['host_name'];
						$xs_hotel_params['qudao_type'] = 0;
						$this->updateXsHotel($xs_hotel_params);
					}
					if(is_numeric(strpos($data['host_name'], 'xl-'))) {
						$xs_hotel_params = array();
						$xs_hotel_params['host_name'] = $params['host_name'];
						$xs_hotel_params['qudao_type'] = 8;
						$this->updateXsHotel($xs_hotel_params);
					}
                }
            }
        } else {
            $status_code = 3;
        }
        $result = array_merge($result,$result_manager[$status_code]);
        return $result;
    }
    
    /**
     * 接口：更新影院账户配置(余额，计费方式，影厅数)(影院调用)
     * @param  array
     * @return array
     * @author ming.nie
     */
    public function updateCinemaHostInfo($params)
	{
        $result = array();
        $result_manager = array(
            0 => array('status_code'=>0,'status_message'=>'更新失败'),
            1 => array('status_code'=>1,'status_message'=>'更新成功'),
            3 => array('status_code'=>3,'status_message'=>'参数错误'),
            4 => array('status_code'=>4,'status_message'=>'主机名错误'),
        );
        $status_code = 0;
        if(isset($params['host_name']) && !empty($params['host_name'])) {
            $current_time = time();
            $cinemaHostModel = M('CinemaHost');
            $stdModel = M();
            
			//nm:顺网网吧版本，1905没有统一分配host_name，是写的配置，这些key是顺网进行配置的
			if(is_numeric(strpos($params['host_name'], 'shunwang'))) {
				$params['host_name'] = 'SHUNWANG';
			}
            //查询主机信息
            $cinema = $this->findByAttr($params);
            if($cinema) {
                $status_code = 1;
				
                //更新影厅信息
                $update_data = array();
                $update_data['id'] = $cinema['id'];
                $update_data['video_hall_count'] = $params['video_hall_count'];
				//nm:1019:kmi不更新
				if(3 != $cinema['type']) {
					$update_data['cinema_name'] = $params['cinema_name'];
				}
                $update_data['user_id'] = 1;
				$update_data['refresh_time'] = $current_time;
				
				//是否重置密码
				if($cinema['init_password']) {
					$result['init_password'] = $cinema['init_password'];
					$update_data['init_password'] = '';
				}
				
                $this->update($update_data);
                
                //组织返回数据
                //当前金额
                $result['money'] = $cinema['money'];
				
                //最新同步的订单
                $result['order_id'] = 0;
                $check_order_sql = 'SELECT order_id FROM mt_cinema_order WHERE host_name = "'.$params['host_name'].'" ORDER BY order_id DESC LIMIT 0,1';
                $check_order_rs = $stdModel->query($check_order_sql);
                if($check_order_rs) {
                    $result['order_id'] = $check_order_rs[0]['order_id'];
                }
                
                //计费方式
                $result['recharge_method'] = $cinema['recharge_method_id'];
				
				//影院计费方式数据
				$result['recharge_data'] = array();
				
				//当前影院类型
				$result['recharge_data']['type'] = $cinema['type'];
				
				//是否试用
				$result['recharge_data']['is_try'] = $cinema['is_try'];
				
				//所属代理商
				$result['recharge_data']['agent_id'] = $cinema['agent_id'];
				
				//扣费先后顺序
				$result['recharge_data']['pay_position'] = $cinema['pay_position'];

                //影院开关
                $result['recharge_data']['power_status'] = $cinema['power_status'];

				//2016计费方式：影院有代理商，以代理商为准，否则以自己计费方式为准
				if(0 < $cinema['agent_id']) {
					$agent = M('Agent')->where('id = "'.$cinema['agent_id'].'"')->find();
					$result['recharge_data']['billing_video_play_type'] = $agent['billing_video_play_type'];
				} else {
					$result['recharge_data']['billing_video_play_type'] = $cinema['billing_video_play_type'];
				}
				
				//片库类型
				$result['recharge_data']['video_data_type'] = $cinema['video_data_type'];
				
				//影院系统平台
				$result['recharge_data']['system_platform'] = $cinema['system_platform'];
				
				//是否支持本地视频
				$result['recharge_data']['is_support_local_video'] = $cinema['is_support_local_video'];
				
				//片库类型Host
				$video_data_type_host_new_options = getVideoDataTypeHostNewOptions();
				$video_data_type_key = $cinema['video_data_type'].'_'.$cinema['video_net'];
				$result['recharge_data']['video_data_type_host'] = $video_data_type_host_new_options[$video_data_type_key];
				!$result['recharge_data']['video_data_type_host'] && $result['recharge_data']['video_data_type_host'] = '';
				$result['recharge_data']['video_copyright_area'] = $cinema['video_copyright_area'];
				$result['recharge_data']['video_copyright_industry'] = $cinema['video_copyright_industry'];
				
				//版权商选项
				$result['recharge_data']['video_film_source_hscm'] = '666666';
				$configModel = M('Config');
				$video_film_source_options = $configModel->where('k="video_film_source"')->find();
				$video_film_source_options = json_decode($video_film_source_options['v'], true);
				$video_film_source_hscm = array_search("华数传媒网络有限公司", $video_film_source_options);
				if($video_film_source_hscm) {
					//该影院是否有华数传媒网络有限公司版权
					$cinema['copyright_user_ids_arr'] = explode(',', $cinema['copyright_user_ids']);
					!$cinema['copyright_user_ids_arr'] && $cinema['copyright_user_ids_arr'] = array();
					foreach($cinema['copyright_user_ids_arr'] as $key => $value) {
						if($video_film_source_hscm == $value) {
							$result['recharge_data']['video_film_source_hscm'] = $video_film_source_hscm;
							break;
						}
					}
				}
				if('666666' == $result['recharge_data']['video_film_source_hscm']) {
					unset($result['recharge_data']['video_film_source_hscm']);
				}
                
				//如果是有老的计费方式，再服务期限内，按照老逻辑处理，否则按新模式处理
				if($cinema['recharge_method_id']) {
					//查询计费方式
					$recharge_method = $this->findRechargeMethod($cinema['recharge_method_id']);
					
					$result['recharge_data']['recharge_method_id'] = $recharge_method['recharge_method_id'];
					$result['recharge_data']['recharge_method_name'] = $recharge_method['recharge_method_name'];
					$result['recharge_data']['description'] = $recharge_method['description'];
					$result['recharge_data']['cost_type'] = $recharge_method['cost_type'];
					$result['recharge_data']['time_count'] = $recharge_method['time_count'];
					$result['recharge_data']['price'] = $recharge_method['price'];
					$result['recharge_data']['last_cost_time'] = $cinema['last_cost_time'];
					$result['recharge_data']['status'] = $cinema['status'];
					$result['recharge_data']['day_count'] = $recharge_method['day_count'];
					
					//基于计费方式，给出消息提醒相关参数
					if(2 == $recharge_method['cost_type']) {
						//期限计费
						//距离下次充值时间间隔
						$use_time = $current_time-$cinema['last_cost_time'];
						$use_date = ceil($use_time/86400);
						$result['recharge_data']['next_cost_day_count'] = $recharge_method['day_count']-$use_date;
						//如果小于0天，进行扣费业务逻辑
						if(0 > $result['recharge_data']['next_cost_day_count']) {
							
							//新模式计费方式
							$result['recharge_data'] = array();
							$result['recharge_data']['cost_type'] = 2;
							$result['recharge_data']['status'] = $cinema['status'];
							$result['recharge_data']['hall_price'] = $cinema['hall_price'];
							$result['recharge_data']['buy_hall_count'] = $cinema['buy_hall_count'];
							$result['recharge_data']['period_count'] = $cinema['period_count'];
							$result['recharge_data']['deduct_period'] = $cinema['deduct_period'];
							$result['recharge_data']['day_count'] = $cinema['deduct_period_day'];
							
							//查看是否有更新的计费方式
							if(0 < $cinema['hall_price_next']) {
								$result['recharge_data']['hall_price'] = $cinema['hall_price_next'];
								$result['recharge_data']['buy_hall_count'] = $cinema['buy_hall_count_next'];
								$result['recharge_data']['period_count'] = $cinema['period_count_next'];
								$result['recharge_data']['deduct_period'] = $cinema['deduct_period_next'];
								$result['recharge_data']['day_count'] = $cinema['deduct_period_day_next'];
							}
							
							//基于新计费方式，计算每次扣款金额，金额够，扣款且更新状态为正常，否则更新状态为停用
							$deduct_money = $result['recharge_data']['hall_price']*$result['recharge_data']['buy_hall_count']*$result['recharge_data']['deduct_period'];
							
							//判断充值业务数据是否满足，金额是否够
							if($deduct_money
							    && $deduct_money <= $cinema['money']) {
								
								$recharge_params = array();
								$recharge_params['money'] = -$deduct_money;
								$recharge_params['description'] = '影院：'.$cinema['host_name'].' ：按扣费周期扣款';
								$recharge_params['cinema_host_id'] = $cinema['id'];
								$recharge_params['recharge_type'] = 2;
								$recharge_params['recharge_method_id'] = 0;
								$recharge_params['user_id'] = 1;
								$sub_result = $this->recharge($recharge_params);
								if(1 == $sub_result['status_code']) {
									//更新影院最后扣费时间
									$update_data = array();
									$update_data['status'] = $cinema['status'];
									$update_data['last_cost_time'] = $current_time;
									
									if(0 < $cinema['hall_price_next']) {
										//重写新的计费模式
										$update_data['hall_price'] = $cinema['hall_price_next'];
										$update_data['buy_hall_count'] = $cinema['buy_hall_count_next'];
										$update_data['period_count'] = $cinema['period_count_next'];
										$update_data['deduct_period'] = $cinema['deduct_period_next'];
										$update_data['deduct_period_day'] = $cinema['deduct_period_day_next'];
										
										//清空下一次计费模式
										$update_data['hall_price_next'] = 0;
										$update_data['buy_hall_count_next'] = 0;
										$update_data['period_count_next'] = 0;
										$update_data['deduct_period_next'] = 0;
										$update_data['deduct_period_day_next'] = 0;
									}
									
									$condition = array();
									$condition['id'] = $cinema['id'];
									$cinemaHostModel->data($update_data)->where($condition)->save();
									$result['recharge_data']['last_cost_time'] = $current_time;
								} else {
									$update_data = array();
									$update_data['status'] = 2;
									$condition = array();
									$condition['id'] = $cinema['id'];
									$cinemaHostModel->data($update_data)->where($condition)->save();
									$result['recharge_data']['status'] = 2;
								}
							} elseif($deduct_money
							    && $deduct_money > $cinema['money']) {
								$update_data = array();
								$update_data['status'] = 2;
								$condition = array();
								$condition['id'] = $cinema['id'];
								$cinemaHostModel->data($update_data)->where($condition)->save();
								$result['recharge_data']['status'] = 2;
							}
						}
					}
					if(1 == $recharge_method['cost_type']) {
						$result['recharge_data']['last_play_count'] = floor($cinema['money']/$recharge_method['price']);
						//资费不足， 修改状态
						if($recharge_method['price'] > $cinema['money']) {
							$result['recharge_data']['status'] = 2;
							$update_data = array();
							$update_data['status'] = 2;
							$condition = array();
							$condition['id'] = $cinema['id'];
							$cinemaHostModel->data($update_data)->where($condition)->save();
						}
					}
				} else {
					//新模式计费方式
					$result['recharge_data']['cost_type'] = 2;
					$result['recharge_data']['status'] = $cinema['status'];
					$result['recharge_data']['hall_price'] = $cinema['hall_price'];
					$result['recharge_data']['buy_hall_count'] = $cinema['buy_hall_count'];
					$result['recharge_data']['period_count'] = $cinema['period_count'];
					$result['recharge_data']['deduct_period'] = $cinema['deduct_period'];
					$result['recharge_data']['day_count'] = $cinema['deduct_period_day'];
					//nm:20170105:如果是包段模式，也要看计费金额是否正常
					$result['recharge_data']['price'] = 0.1;
					
					//使用时间
					$use_time = $current_time-$cinema['last_cost_time'];
					
					//使用天数
					$use_date = ceil($use_time/86400);
					$result['recharge_data']['next_cost_day_count'] = $cinema['deduct_period_day']-$use_date;
					//如果小于0天，进行扣费业务逻辑
					if(0 > $result['recharge_data']['next_cost_day_count']) {
						
						//查看是否有更新的计费方式
                        if(0 < $cinema['hall_price_next']) {
                            $result['recharge_data']['hall_price'] = $cinema['hall_price_next'];
							$result['recharge_data']['buy_hall_count'] = $cinema['buy_hall_count_next'];
							$result['recharge_data']['period_count'] = $cinema['period_count_next'];
							$result['recharge_data']['deduct_period'] = $cinema['deduct_period_next'];
							$result['recharge_data']['day_count'] = $cinema['deduct_period_day_next'];
                        }
						
						//基于新计费方式，计算每次扣款金额，金额够，扣款且更新状态为正常，否则更新状态为停用
						$deduct_money = $result['recharge_data']['hall_price']*$result['recharge_data']['buy_hall_count']*$result['recharge_data']['deduct_period'];
						
						//判断充值业务数据是否满足，金额是否够
						if($deduct_money
							&& $deduct_money <= $cinema['money']) {
							
							$recharge_params = array();
							$recharge_params['money'] = -$deduct_money;
							$recharge_params['description'] = '影院：'.$cinema['host_name'].' ：按扣费周期扣款';
							$recharge_params['cinema_host_id'] = $cinema['id'];
							$recharge_params['recharge_type'] = 2;
							$recharge_params['recharge_method_id'] = 0;
							$recharge_params['user_id'] = 1;
							$sub_result = $this->recharge($recharge_params);
							if(1 == $sub_result['status_code']) {
								//更新影院最后扣费时间，与计费方式
								$update_data = array();
								$update_data['status'] = 1;
								$update_data['last_cost_time'] = $current_time;
								
								if(0 < $cinema['hall_price_next']) {
									//重写新的计费模式
									$update_data['hall_price'] = $cinema['hall_price_next'];
									$update_data['buy_hall_count'] = $cinema['buy_hall_count_next'];
									$update_data['period_count'] = $cinema['period_count_next'];
									$update_data['deduct_period'] = $cinema['deduct_period_next'];
									$update_data['deduct_period_day'] = $cinema['deduct_period_day_next'];
									
									//清空下一次计费模式
									$update_data['hall_price_next'] = 0;
									$update_data['buy_hall_count_next'] = 0;
									$update_data['period_count_next'] = 0;
									$update_data['deduct_period_next'] = 0;
									$update_data['deduct_period_day_next'] = 0;
								}
								
								$condition = array();
								$condition['id'] = $cinema['id'];
								$cinemaHostModel->data($update_data)->where($condition)->save();
								$result['recharge_data']['last_cost_time'] = $current_time;
							} else {
								$update_data = array();
								$update_data['status'] = 2;
								$condition = array();
								$condition['id'] = $cinema['id'];
								$cinemaHostModel->data($update_data)->where($condition)->save();
								$result['recharge_data']['status'] = 2;
							}
						} else {
							$update_data = array();
							$update_data['status'] = 2;
							$condition = array();
							$condition['id'] = $cinema['id'];
							$cinemaHostModel->data($update_data)->where($condition)->save();
							$result['recharge_data']['status'] = 2;
						}
					}
				}
				
				//如果影院云端状态为试用或者先使用再扣费，那么影院线下系统也应该为正常，保证可以正常使用，模拟正常使用的配置
				if(1 == $cinema['is_try'] || 2 == $cinema['pay_position']) {
					$result['recharge_data']['status'] = 1;
					$result['recharge_data']['cost_type'] = 2;
					$result['recharge_data']['next_cost_day_count'] = 300;
					
					//nm: 2016-12-06:如果线下可以正常下单（那么，线上状态要更新为1：说明先使用后付费，或者试用，满足线上下单）
					$update_data = array();
					$update_data['status'] = 1;
					$condition = array();
					$condition['id'] = $cinema['id'];
					$cinemaHostModel->data($update_data)->where($condition)->save();
				}

                //更新影院状态及更新时间,试用时间
                $find=M('cinema_host')->field('status,is_try,try_day_max')->where(array('host_name'=>$params['host_name']))->find();
                if(empty($result['recharge_data']['status'])){
                    $result['recharge_data']['status']=$find['status'];
                }
                //停用影院
                if($cinema['power_status']==2){
                    $result['recharge_data']['status']=0;
                }
                $result['recharge_data']['update_time']=time();
                $result['recharge_data']['is_try']=$find['is_try'];
                $result['recharge_data']['try_day_max']=$find['try_day_max'];

			} else {
				$status_code = 4;
			}
		} else {
			$status_code = 3;
		}

        //更新系统版本号
        M('CinemaHost')->where(array('host_name'=>$params['host_name']))
                ->save(array('versions'=>$params['versions']));
        $result = array_merge($result,$result_manager[$status_code]);
        return $result;
    }
    
    /**
     * 接口：同步影院订单数据(影院调用)
     * @param  array
     * @return array
     * @author ming.nie
     */
    public function syncOrderList($params){
        $result = array();
        $result_manager = array(
            0 => array('status_code'=>0,'status_message'=>'订单数据同步失败'),
            1 => array('status_code'=>1,'status_message'=>'订单数据同步成功'),
            3 => array('status_code'=>3,'status_message'=>'参数错误'),
        );
        $status_code = 0;
        if(isset($params['host_name']) && !empty($params['host_name'])
           && isset($params['order_list']) && !empty($params['order_list'])) {
            $current_time = time();
            
            //查询影院计费方式
            $cinema_host = $this->findByAttr($params);
            $current_recharge_method = $this->findRechargeMethod($cinema_host['recharge_method_id']);
            
            $model = M('CinemaOrder');
            $result['order_ids'] = array();
            //遍历订单，插入数据
            foreach($params['order_list'] as $key => $value) {
                //查询订单是否已同步
                $check_order_condition = array();
                $check_order_condition['host_name'] = $params['host_name'];
                $check_order_condition['order_id'] = $value['order_id'];
                $check_order_rs = $model->where($check_order_condition)->find();
                if(!$check_order_rs) {
                    $order_data = $value;
                    $order_data['host_name'] = $params['host_name'];
                    $order_data['create_user_id'] = 1;
                    $order_data['create_time'] = $current_time;
                    $order_data['update_user_id'] = 1;
                    $order_data['update_time'] = $current_time;
                    
                    $rs = $model->data($order_data)->add();
					
                    if($rs) {
						//数据插入成功，记录订单id，反馈给影院
                        $result['order_ids'][] = $value['order_id'];
                        
						//订单记录成功，如果是正式使用，且计费方式是按次数扣费，就按照计费方式详情进行扣费
						if(2 == $cinema_host['is_try']) {
							//声明当前计费方式
							$recharge_method = $current_recharge_method;
							
							//查询指定的计费方式
							if(array_key_exists('recharge_method_id', $value) && $value['recharge_method_id']) {
								$recharge_method = $this->findRechargeMethod($value['recharge_method_id']);
							}
							
							//如果计费方式是按次数扣费，且不是第一次播放，进行扣款
							if(1 == $recharge_method['cost_type']
							   && 0 < $value['deduction']) {
								$recharge_params = array();
								$recharge_params['money'] = -$recharge_method['price'];
								$recharge_params['description'] = '影院：'.$cinema_host['host_name'].' 订单：'.$value['order_sn'].' 扣款';
								$recharge_params['cinema_host_id'] = $cinema_host['id'];
								$recharge_params['recharge_type'] = 2;
								$recharge_params['user_id'] = 1;
								$sub_result = $this->recharge($recharge_params);
							}
						}
                    }
                }
            }
            if($result['order_ids']) {
                $status_code = 1;
            }
        } else {
            $status_code = 3;
        }
        $result = array_merge($result,$result_manager[$status_code]);
        return $result;
    }
	
	//账户到款确认，完成充值
	public function completeRecharge($params)
	{
		$result = array();
        $result_manager = array(
            0 => array('status_code'=>0,'status_message'=>'完成交易失败'),
            1 => array('status_code'=>1,'status_message'=>'完成交易成功'),
            3 => array('status_code'=>3,'status_message'=>'交易参数错误'),
			4 => array('status_code'=>4,'status_message'=>'交易已完成'),
        );
        $status_code = 0;
        if(isset($params['recharge_log_id']) && $params['recharge_log_id']) {
            $model = M('RechargeLog');
			$current_time = time();
            
			//查找当前交易
			$condition = array();
			$condition['recharge_log_id'] = $params['recharge_log_id'];
			$current_recharge_log = $model->where($condition)->find();
			
			if($current_recharge_log) {
				if(0 == $current_recharge_log['is_complete']) {
					
					//查询当前影院信息
					$cinemaHostModel = M('CinemaHost');
					$cinema = $this->find($current_recharge_log['cinema_host_id']);
					
					//计算影厅当前余额
					$balance = $cinema['money'] + $current_recharge_log['money'];
					
					//更新影院用户金额
					$update_data = array();
					$update_data['money'] = $balance;
					$condition = array();
					$condition['id'] = $current_recharge_log['cinema_host_id'];
					$db_result = $cinemaHostModel->data($update_data)->where($condition)->save();
					
					//充值的时候，检测当前影院计费方式，与账户余额判断是否需要自动扣费
					$recharge_method = $this->findRechargeMethod($cinema['recharge_method_id']);
					if($db_result
					   && 1 == $current_recharge_log['recharge_type']) {
						//充值成功
						$status_code = 1;
						
						$need_cost = 0;
						
						//包段计费模式，基于最后扣费时间，判断是否需要自动扣费
						if(($recharge_method && 2 == $recharge_method['cost_type'] && 0 == $cinema['last_cost_time'])
						   || (!$recharge_method && 0 == $cinema['last_cost_time'])) {
							$need_cost = 1;
						}
						
						//老模式：期限类，已扣款，判断是否超过期限。超期，就用新的计费方式扣费，并且取消老的选项计费方式
						if(!$need_cost
							&& $recharge_method
							&& 2 == $recharge_method['cost_type']) {
							$use_time = $current_time-$cinema['last_cost_time'];
							$use_date = ceil($use_time/86400);
							if($use_date > $recharge_method['day_count']) {
								$need_cost = 1;
								$update_data = array();
								$update_data['last_cost_time'] = 0;
								$update_data['recharge_method_id'] = 0;
								$update_data['next_recharge_method_id'] = 0;
								$condition = array();
								$condition['id'] = $current_recharge_log['cinema_host_id'];
								$cinemaHostModel->data($update_data)->where($condition)->save();
							}
						}
						
						//新模式：期限类，已扣款，判断是否超过期限。超期，用新的计费方式扣费
						if(!$need_cost
							&& !$recharge_method
							&& $cinema['hall_price']) {
							$use_time = $current_time-$cinema['last_cost_time'];
							$use_date = ceil($use_time/86400);
							if($use_date > $cinema['deduct_period_day']) {
								$need_cost = 1;
								$update_data = array();
								$update_data['last_cost_time'] = 0;
								$update_data['recharge_method_id'] = 0;
								$update_data['next_recharge_method_id'] = 0;
								$condition = array();
								$condition['id'] = $current_recharge_log['cinema_host_id'];
								$cinemaHostModel->data($update_data)->where($condition)->save();
							}
						}
						
						if(1 == $need_cost) {
							//查看是否有更新的计费方式，有的话，就用新的计费方式
							if(0 < $cinema['hall_price_next']) {
								$cinema['hall_price'] = $cinema['hall_price_next'];
								$cinema['buy_hall_count'] = $cinema['buy_hall_count_next'];
								$cinema['period_count'] = $cinema['period_count_next'];
								$cinema['deduct_period'] = $cinema['deduct_period_next'];
								$cinema['deduct_period_day'] = $cinema['deduct_period_day_next'];
							}
							
							//基于计费方式，计算每次扣款金额，金额够，扣款且更新状态为正常，否则更新状态为停用
							$deduct_money = $cinema['hall_price']*$cinema['buy_hall_count']*$cinema['deduct_period'];
							if($deduct_money) {
								if($balance >= $deduct_money) {
									$recharge_params = array();
									$recharge_params['money'] = -$deduct_money;
									$recharge_params['description'] = '影院：'.$cinema['host_name'].' ：按扣费周期扣款';
									$recharge_params['cinema_host_id'] = $current_recharge_log['cinema_host_id'];
									$recharge_params['recharge_type'] = 2;
									$recharge_params['recharge_method_id'] = 0;
									$recharge_params['user_id'] = 1;
									$sub_result = $this->recharge($recharge_params);
									if(1 == $sub_result['status_code']) {
										//更新影院最后扣费时间
										$update_data = array();
										$update_data['status'] = 1;
										$update_data['last_cost_time'] = $current_time;
										$update_data['deduct_period_day'] = $cinema['deduct_period']*31;
										
										//查看是否有更新的计费方式，有的话，就更新老的，清空旧的
										if(0 < $cinema['hall_price_next']) {
											$update_data['hall_price'] = $cinema['hall_price_next'];
											$update_data['buy_hall_count'] = $cinema['buy_hall_count_next'];
											$update_data['period_count'] = $cinema['period_count_next'];
											$update_data['deduct_period'] = $cinema['deduct_period_next'];
											
											$update_data['hall_price_next'] = 0;
											$update_data['buy_hall_count_next'] = 0;
											$update_data['period_count_next'] = 0;
											$update_data['deduct_period_next'] = 0;
											$update_data['deduct_period_day_next'] = 0;
										}
										
										$condition = array();
										$condition['id'] = $current_recharge_log['cinema_host_id'];
										$cinemaHostModel->data($update_data)->where($condition)->save();
									}
								} else {
									$update_data = array();
									$update_data['status'] = 2;
									$condition = array();
									$condition['id'] = $current_recharge_log['cinema_host_id'];
									$cinemaHostModel->data($update_data)->where($condition)->save();
								}
							}
						}
					}
					
				} else {
					$status_code = 4;
				}
			} else {
				$status_code = 3;
			}
        } else {
            $status_code = 3;
        }
        $result = array_merge($result,$result_manager[$status_code]);
        return $result;
	}
	
	//更新数据到小帅表
	public function updateXsHotel($params)
	{
		$result = true;
		
		$model = M('XsHotel');
		//验证是否有该主机
		$condition = array();
		$condition['host_name'] = $params['host_name'];
		$check = $model->where($condition)->find();
		if(!$check) {
			$result = $model->data($params)->add();
		} else {
			$result = $model->data($params)->where($condition)->save();
		}
		
		return $result;
	}

    //影院端更新缓存
    public function updataCache(){
        callWebInterfaceData(array('class'=>'CinemaCache','method'=>'updataCache'));
    }
    public function getCinemaDescList(){
        $page=I('p',1,'strip_tags');
        $cinema_code=I('cinema_code','','strip_tags');
        $cinema_name=I('cinema_name','','strip_tags');
        $Cinema=M('cinema_host');
        $result = array();
        $where['_string']='1=1';
        if($cinema_code){
            $where['cinema_code']=array('eq',$cinema_code);
        }
        if($cinema_name){
            $where['cinema_name']=array('eq',$cinema_name);
        }
        $count=$Cinema->where($where)->count('id');
        $data=$Cinema->where($where)->page($page,10)->select();
        $pager = new \Think\Page2($count,10);
        $result['data']=$data;
        $result['pager'] = $pager->show();
        return $result;
    }
}
